package org.alex.sample.web;

import java.io.File;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

	//@RequestMapping(value = "/upload")
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpSession session, ModelMap model) {
		String path = session.getServletContext().getRealPath("upload"); //获取绝对路径
		String fileName = file.getOriginalFilename(); //获取原文件名
		System.out.println(path);
		File targetFile = new File(path, fileName); //创建文件
		if(!targetFile.exists()) {
			targetFile.mkdirs(); //创建upload文件夹
		}
		
		//保存
		try {
			file.transferTo(targetFile); //保存文件
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		model.addAttribute("message", "文件上传成功");
		return "result";
	}
	
}
